<template>
  <div>
    <card class="list-card-container">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="handleAdd">新增</t-button>
          <t-button :disabled="single" theme="default" @click="handleUpdate">修改</t-button>
          <t-button :disabled="multiple" theme="default" @click="handleDelete">删除</t-button>
          <t-button theme="default" @click="getList()">刷新</t-button>
        </div>
        <t-input v-model="deptName" class="search-input" placeholder="请输入你需要搜索的内容" clearable>
          <template #suffix-icon>
            <search-icon size="20px" />
          </template>
        </t-input>
      </t-row>
      <div class="table-container">
        <t-loading :loading="loading" show-overlay>
          <t-table
            :data="userList"
            row-key="id"
            :columns="columns"
            :selected-row-keys="selectedRowKeys"
            @select-change="handleSelectionChange"
          >
            <template #status_slot="{ row }">
              <!-- <t-switch size="large" v-model="row.is_active"
                @change="handleStatusChange(row)"></t-switch> -->
                <t-tag :theme="row.is_active ? 'success' : 'danger' ">{{ row.is_active ? '正常' : '停用' }}</t-tag>
          </template>
            <template #role-slot="{ row }">
              <template v-if="row.role.length > 0">
                <t-dropdown  :minColumnWidth="88">
                  <t-button variant="text">{{ row.role[0].roleName }}</t-button>
                  <t-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(role,index) in row.role" :key="index">{{ role.roleName }}</el-dropdown-item>
                  </t-dropdown-menu>
                </t-dropdown>
              </template>
              <template v-else>
                <span>暂无关联角色</span>
              </template>
            </template>
            <template #operation="{ row }">
              <a @click="handleUpdate(row)">修改</a>
              <a class="link" @click="handleDelete(row)">删除</a>
            </template>
          </t-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </t-loading>
      </div>
    </card>
    <!-- 添加或修改岗位对话框 -->
    <t-dialog :header="title" :visible.sync="open" width="600px" @confirm="submitForm">
      <div slot="body">
        <t-form ref="form" :data="form" :reset-type="resetType" :rules="rules" label-width="80px" colon>
          <t-form-item label="用户昵称" name="name">
            <t-input v-model="form.name" placeholder="请输入内容"></t-input>
          </t-form-item>
          <t-form-item label="手机号码" name="mobile">
            <t-input v-model="form.mobile" placeholder="请输入内容"></t-input>
          </t-form-item>
          <t-form-item label="邮箱" name="postSort">
            <t-input v-model="form.postSort" placeholder="请输入内容"></t-input>
          </t-form-item>
            <t-form-item label="用户名称" v-if="form.id == undefined" name="username">
            <t-input v-model="form.username" placeholder="请输入用户名称"></t-input>
          </t-form-item>
            <t-form-item v-if="form.id == undefined" label="用户密码" name="password">
            <t-input v-model="form.password" type="password" placeholder="请输入用户密码"></t-input>
          </t-form-item>
          <t-form-item label="状态">
            <t-radio-group v-model="form.is_active">
              <t-radio v-for="dict in statusOptions" :key="dict.dictValue" :value="dict.dictValue"
                >{{ dict.dictLabel }}
              </t-radio>
            </t-radio-group>
          </t-form-item>
          <t-form-item label="用户性别">
            <t-select v-model="form.gender" placeholder="请选择内容">
              <t-option
                v-for="dict in sexOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </t-select>
          </t-form-item>
          <t-form-item label="角色">
            <t-select v-model="form.roleIds" placeholder="请选择内容">
              <t-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
                :disabled="item.status == 0"
              />
            </t-select>
          </t-form-item>
          <t-form-item label="备注" name="remark">
            <t-textarea v-model="form.remark" placeholder="请输入内容"></t-textarea>
          </t-form-item>
        </t-form>
      </div>
    </t-dialog>
  </div>
</template>
<script >
import { SearchIcon } from 'tdesign-icons-vue';
import Card from '@/components/card/index.vue';
import {
  addUser,
  changeUserStatus,
  // delUser,
  // exportUser,
  getUser,
  // importsUser,
  // importTemplate,
  listUser,
  // resetUserPwd,
  updateUser
} from '@/api/vadmin/permission/user';

export default {
  components: {
    SearchIcon,
    Card,
  },
  data() {
    return {
      resetType: 'empty',
      selectedRowKeys: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 18,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [
        { dictLabel: '正常', dictValue: true },
        { dictLabel: '停用', dictValue: false },
      ],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        search: undefined,
        username: undefined,
        mobile: undefined,
        is_active: undefined,
        deptId: undefined,
      },
      // 列信息
      columns: [
        {
          colKey: 'row-select',
          type: 'multiple',
          width: 80,
        },
        {
          colKey: 'id',
          title: '用户编号',
        },
        {
          colKey: 'username',
          title: '用户账号',
        },
        {
          colKey: 'name',
          title: '姓名',
        },
        {
          colKey: 'role',
          title: '关联角色',
          cell: 'role-slot',
        },
        {
          colKey: 'mobile',
          title: '手机号码',
        },
        {
          // colKey: 'status',
          title: '状态',
          cell: 'status_slot'
        },
        {
          colKey: 'create_datetime',
          title: '创建时间',
          cell: 'time-slot'
        },
        {
          colKey: 'operation',
          title: '操作',
          width: 120,
          cell: 'operation'
        },
      ],
      // 表单校验
      rules: {
        username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
        email: [
          {
            type: 'email',
            message: "'请输入正确的邮箱地址",
            trigger: ['blur', 'change'],
          },
        ],
        mobile: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then((response) => {
        this.userList = response.data.results;
        this.total = response.data.count;
        this.loading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.is_active === true ? "启用" : "停用";
      changeUserStatus(row.id, row.is_active).then(() => {
        this.$$message.success(`${text  }成功`);
      })
      // this.$confirm(`确认要"${  text  }""${  row.username  }"用户吗?`, "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => .catch(() => {
      //   row.is_active = row.is_active === false;
      // });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        username: undefined,
        name: undefined,
        password: undefined,
        mobile: undefined,
        email: undefined,
        gender: undefined,
        is_active: false,
        remark: undefined,
        // postIds: [],
        roleIds: [],
      };
      // this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.deptId = '';
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    // 多选框选中数据
    handleSelectionChange(value) {
      this.selectedRowKeys = value;
      this.ids = value.map((item) => item.id);
      this.single = value.length !== 1;
      this.multiple = !value.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.reset();
      getUser().then(response => {
        this.title = "添加用户";
        this.open = true;
        // this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      // getUser(id).then(response => {
      //   const {data} = response.data;
      //   data.postIds = response.data.postIds;
      //   data.roleIds = response.data.roleIds;
      //   this.form = data;
      //   this.postOptions = response.data.posts;
      //   this.roleOptions = response.data.roles;
      //   this.open = true;
      //   this.title = "修改用户";
      //   this.form.password = "";
      // });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt(`请输入"${row.username}"的新密码`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        // resetUserPwd(row.id, md5(value)).then(response => {
        //   this.msgSuccess(`修改成功，新密码是：${  value}`);
        // });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateUser(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      // this.$confirm(`是否确认删除用户编号为"${  userIds  }"的数据项?`, "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => delUser(userIds)).then(() => {
      //   this.getList();
      //   this.msgSuccess("删除成功");
      // });
    },
    /** 导出按钮操作 */
    handleExport() {
      const { queryParams } = this;
      // this.$confirm("是否确认导出所有用户数据项?", "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => exportUser(queryParams)).then(response => {
      //   this.download(response.data.file_url, response.data.name);
      // });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入';
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      // importTemplate().then(response => {
      //   this.download(response.data.file_url, response.data.name);
      // });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 是否更新已经存在的用户数据
      // importsUser({ file_url: response.data.file_url, updateSupport: this.upload.updateSupport }).then(response => {
      //   this.$alert("导入成功！", "导入结果", { dangerouslyUseHTMLString: true });
      //   this.getList();
      // });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables';

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}

.left-operation-container {
  padding: 0 0 6px 0;
  margin-bottom: 16px;

  .selected-count {
    display: inline-block;
    margin-left: 8px;
    color: @text-color-secondary;
  }
}

.search-input {
  width: 360px;
}
.t-popup__content{
  line-height: 30px;
  text-align: center !important;
}
</style>
